const fs = require("fs");
const path = require("path");

const koa = require("koa");
const app = new koa();

const body = require("koa-body");
const koaStatic = require("koa-static");
// const Router = require("koa-router");
const Router = require("./router");

app.use(
  body({
    multipart: true, // 允许上传多个文件
    encoding: "gzip",
    formidable: {
      uploadDir: path.join(__dirname, "upload/"), // 设置文件上传目录
      keepExtensions: true, // 保持文件的后缀
      maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
      onFileBegin: (name, file) => {
        // 文件上传前的设置
        console.log(`name: ${name}`);
        console.log(file);
      },
    },
  })
);
app.use(koaStatic(__dirname));
app.use(koaStatic(path.resolve(__dirname, "upload")));

// 封装router路由来处理不同的路径地址请求，以及不同的method
/* app.use(async (ctx, next) => {
  if (ctx.path === "/form" && ctx.method === "GET") {
    ctx.set("Content-Type", "text/html;charset=utf-8");
    ctx.body = fs.createReadStream("./form.html");
  } else {
    await next();
  }
});
app.use((ctx, next) => {
  if (ctx.path === "/login" && ctx.method === "POST") {
    ctx.body = ctx.request.body;
  }
}); */
let router = new Router();
app.use(router.routes());
// app.use(router.allowedMethods());

router.get("/", async (ctx, next) => {
  // ctx.body = "home";
  console.log(1);
  next();
});
router.get("/", async (ctx, next) => {
  // ctx.body = "home";
  console.log(2);
});
// router.get("/form", async (ctx, next) => {
//   ctx.set("ContentType", "text/html");
//   ctx.type = "html";
//   ctx.body = fs.createReadStream("./form.html");
// });
// router.post("/login", async (ctx, next) => {
//   console.log("login", ctx);
//   ctx.body = ctx.request.body;
// });

app.listen(3000);
